<script setup lang="ts" name="PaneJobExecution">
import { mapState } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import EventEmitter from '@/utils/EventEmitter'
import {
  isJobExecutable,
  getJobPriorityValue,
  getRetryTimeCycleValue,
  retryTimeCycleVisible,
  setJobPriorityValue,
  setRetryTimeCycleValue,
  jobPriorityVisible
} from '../../utils/jobExecution'

const mapStates = computed(() => {
  return mapState(useModelerStore, ['getActive'])
})

const rtVisible = ref(false)
const retryTimeCycle = ref('')
const getRetryTimeCycle = () => {
  rtVisible.value = retryTimeCycleVisible(mapStates.value.getActive())
  retryTimeCycle.value = getRetryTimeCycleValue(mapStates.value.getActive()) || ''
}
const setRetryTimeCycle = (v) => {
  setRetryTimeCycleValue(mapStates.value.getActive(), v)
}

const jpVisible = ref(false)
const jobPriority = ref('')
const getJobPriority = () => {
  jpVisible.value = jobPriorityVisible(mapStates.value.getActive())
  jobPriority.value = getJobPriorityValue(mapStates.value.getActive()) || ''
}
const setJobPriority = (v) => {
  setJobPriorityValue(mapStates.value.getActive(), v)
}

const eventEmitterListener = () => {
  if (isJobExecutable(mapStates.value.getActive())) {
    getRetryTimeCycle()
    getJobPriority()
  }
}

onBeforeUnmount(() => {
  EventEmitter.removeListener('element-update', eventEmitterListener)
})

onMounted(() => {
  getRetryTimeCycle()
  getJobPriority()
  EventEmitter.on('element-update', eventEmitterListener)
})
</script>

<template>
  <el-collapse-item name="job-execution">
    <template #title>
      <div class="collapse-header">
        <svg-icon icon="ri:file-history-fill"></svg-icon>
        <h2>执行作业</h2>
      </div>
    </template>
    <el-form-item v-if="rtVisible" label="重试时间周期">
      <el-input v-model="retryTimeCycle" maxlength="32" @change="setRetryTimeCycle" />
    </el-form-item>
    <el-form-item v-if="jpVisible" label="任务优先级">
      <el-input v-model="jobPriority" maxlength="20" @change="setJobPriority" />
    </el-form-item>
  </el-collapse-item>
</template>

<style scoped lang="scss">
.el-collapse-item {
  :deep(.el-collapse-item__header) {

    .collapse-header {
      display: flex;
      flex: 1;
      align-items: center;
      padding: 0 12px;

      .el-icon {
        margin-right: 6px;
        font-size: 20px !important;
      }

      h2 {
        font-weight: bold;
        font-size: 14px;
      }
    }

    .el-icon {
      font-size: 18px;
    }
  }

  :deep(.el-collapse-item__content) {
    padding-right: 12px;
    padding-bottom: 12px;
    padding-left: 12px;
  }
}
</style>
